package com.example.taobaounion.view.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.bumptech.glide.Glide;
import com.example.taobaounion.model.domain.HomePagerContent;
import com.example.taobaounion.utils.UrlUtils;

import java.util.ArrayList;
import java.util.List;

public class LooperPagerAdapter extends PagerAdapter {
    private List<HomePagerContent.DataBean> data = new ArrayList<>();
    private HomePageContentAdapter.onListenerItemClickListener mClickListener;

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        // Deal the overflow
        int realPosition = position % data.size();
        ImageView imageView = new ImageView(container.getContext());

        imageView.setOnClickListener(v -> {
            if (mClickListener != null) {
                mClickListener.onItemClick(data.get(realPosition));
            }
        });

        // 根据容器获取需要的图片大小
        // 减少数据量，省流量，更快

        int measuredHeight = container.getMeasuredHeight();
        int measuredWidth = container.getMeasuredWidth();

        int imageSize = Math.max(measuredWidth, measuredHeight) / 2;

        String coverUrl = UrlUtils.getCoverPath(data.get(realPosition).getPict_url(), imageSize);

        Glide.with(container.getContext()).load(coverUrl).into(imageView);

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        imageView.setLayoutParams(layoutParams);

        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        container.addView(imageView);
        return imageView;
    }

    public void setData(List<HomePagerContent.DataBean> contents) {
        data.clear();
        data.addAll(contents);
        notifyDataSetChanged();
    }

    public int getDataSize() {
        return data.size();
    }

    public void setOnLoopPageItemClickListener(HomePageContentAdapter.onListenerItemClickListener listener) {
        mClickListener = listener;
    }
}
